package cn.chaozhoubang.vmall.backend.controller.impl;

import cn.chaozhoubang.vmall.backend.controller.ManagerController;
import cn.chaozhoubang.vmall.backend.mapper.ManagerMapper;
import cn.chaozhoubang.vmall.backend.mapper.RoleMapper;
import cn.chaozhoubang.vmall.backend.model.SpManager;
import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;

@RestController
@RequestMapping("/api/private/v1")
public class ManagerControllerImpl implements ManagerController {

    private ManagerMapper managerMapper;
    private RoleMapper roleMapper;

    private JSONObject buildMeta(int status, String msg) {
        final JSONObject meta = new JSONObject();
        meta.set("status", status);
        meta.set("msg", msg);
        return meta;
    }

    private JSONObject buildData(SpManager manager, String token) {
        final JSONObject data = new JSONObject();
        if(manager != null) {
            data.set("id", manager.getMgId())
                    .set("rid", manager.getRoleId())
                    .set("username", manager.getMgName())
                    .set("mobile", manager.getMgMobile())
                    .set("email", manager.getMgEmail());
        }
        data.set("token", token);
        return data;
    }

    private JSONObject buildResult(JSONObject meta, JSONObject data) {
        final JSONObject res = new JSONObject();
        res.set("meta", meta);
        res.set("data", data);
        return res;
    }

    @Override
    @RequestMapping(value = "/login", produces = "application/json;charset=UTF-8")
    public String userLogin(@RequestBody String jsonStr) {
        if(jsonStr == null) return "{}";
        JSONObject json = JSONUtil.parseObj(jsonStr);
        String username = (String) json.get("username");
        String password = (String) json.get("password");
        System.out.println(username + ": " + password);


        // 查询管理员
        QueryWrapper<SpManager> wrapper = new QueryWrapper<>();
        wrapper.eq("mg_name", username);
        SpManager manager = managerMapper.selectOne(wrapper);
        if(manager == null) {
            final JSONObject meta = buildMeta(-1, "找不到用户!");
            return buildResult(meta, null).toString();
        }
        // 验证密码
        String md5 = DigestUtil.md5Hex(password);
        if(!md5.equals(manager.getMgPwd())) {
            final JSONObject meta = buildMeta(-1, "用户名或密码错误!");
            return buildResult(meta, null).toString();
        }

        final String key = "key";
        final HashMap<String, Object> payload = new HashMap<>();
        final DateTime now = DateTime.now();
        final DateTime expireTime = now.offset(DateField.HOUR, 10);
        payload.put(JWTPayload.ISSUED_AT, now);         // 签发时间
        payload.put(JWTPayload.EXPIRES_AT, expireTime); // 过期时间
        payload.put(JWTPayload.NOT_BEFORE, now);        // 生效时间
        payload.put("username", username);
        payload.put("password", md5);
        final String token = JWTUtil.createToken(payload, key.getBytes());
        System.out.println(token);

        final JSONObject meta = buildMeta(200, "登陆成功!");
        final JSONObject data = buildData(manager, token);
        return buildResult(meta, data).toString();
    }


    @Autowired
    public void setManagerMapper(ManagerMapper managerMapper) {
        this.managerMapper = managerMapper;
    }

    @Autowired
    public void setRoleMapper(RoleMapper roleMapper) {
        this.roleMapper = roleMapper;
    }
}
